package net.yebaihe.wc;

import java.util.Date;
import java.util.HashMap;

import net.yebaihe.wc.DataMan.MSGTYPE;
import net.yebaihe.wc.Dishes.OrderSimpleCursorAdapter;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Notifications extends StateMachine{

	private ListView lstNotification;
	private SQLiteDatabase listdb;

	class NotifySimpleCursorAdapter extends SimpleCursorAdapter{
		public NotifySimpleCursorAdapter(Context context, int layout, Cursor c,
				String[] from, int[] to) {
			super(context, layout, c, from, to);
		}
		@Override  
		public void bindView(View view, Context context, Cursor cursor) {  
			super.bindView(view, context, cursor);
			TextView v=(TextView) view.findViewById(R.id.txtdate);
			TextView vcnt=(TextView) view.findViewById(R.id.txttitle);
			
			String date="未指定时间";
			if (cursor.getString(2)!=null){
				Date d=new Date(cursor.getLong(6));
				date=""+(d.getYear()+1900)+"-"+d.getMonth()+"-"+d.getDate()+ " "+d.getHours()+":"+d.getMinutes();
			}
			v.setText(date);
			
			if (cursor.getInt(7)==0){
				v.setTextColor(0xFFFF0000);
				vcnt.setTextColor(0xFF000000);
			}
			else{
				v.setTextColor(0xFF8c8c8c);
				vcnt.setTextColor(0xFF8c8c8c);
			}
			
		}		
	}
	
	@Override
	public void HandleMessage(MSGTYPE msgtype, boolean ret,
			HashMap<String, String> params) {
		super.HandleMessage(msgtype, ret, params);
		if (msgtype==MSGTYPE.CHECK_NOTIFICATIONS){
			refreshNotifications();
		}
	}

	@Override
	protected String getTopbarTitle() {
		return "消息中心";
	}
	
	@Override
	protected void prepareClient(View client) {
		lstNotification=(ListView)client.findViewById(R.id.lstNotification);
		listdb=MyHelper.get(this).getReadableDatabase();
		refreshNotifications();
	}

	private void refreshNotifications() {
		if (listdb!=null){
			UserInfoData userdata = MyHelper.get(this).getCurrUserInfoData(getWCAppContext().email);
			if (userdata==null) return;
			Cursor c=listdb.rawQuery("select * from notifications where touid="+userdata._id+" order by timestamp desc", null);
			startManagingCursor(c);
			ListAdapter listAdapter = new NotifySimpleCursorAdapter(this, R.layout.itemnotification,
					c,
					new String[]{"message"},
					new int[]{R.id.txttitle});
			lstNotification.setAdapter(listAdapter);
			lstNotification.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					processNotify(arg3);
				}
			});
			
			lstNotification.setOnItemLongClickListener(new OnItemLongClickListener(){
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					final long nid=arg3;
					Cursor c=listdb.rawQuery("select * from notifications where _id="+arg3, null);
					c.moveToFirst();
					new AlertDialog.Builder(Notifications.this).setTitle(R.string.app_name)
					.setMessage("您确定要删除这条消息吗："+c.getString(1)+" ?")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							Cursor c=listdb.rawQuery("select * from notifications where _id="+nid, null);
							c.moveToFirst();
							if (c.getInt(4)==StateMachine.NOTIFY_LEFT_SESSION){
								final long sessionid=Long.parseLong(c.getString(5));
								new AlertDialog.Builder(Notifications.this).setTitle(R.string.app_name)
									.setMessage("您想放弃本次点餐吗？")
									.setPositiveButton("确定", new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface arg0, int arg1) {
											SQLiteDatabase wdb = MyHelper.get(Notifications.this).getWritableDatabase();
											wdb.delete("sessions", "_id="+sessionid, null);
											wdb.delete("sessiondish", "sessionid="+sessionid, null);
											wdb.delete("sessionuser", "sessionid="+sessionid, null);
											wdb.delete("notifications", "_id="+nid, null);
											if (getWCAppContext().sessionid==sessionid){
												getWCAppContext().sessionid=-1;
											}
											wdb.close();
											refreshNotifications();
											DataMan.get(Notifications.this).checkNotifies();
											Toast.makeText(Notifications.this, "点餐已放弃!", Toast.LENGTH_SHORT).show();
										}
									})
									.setNegativeButton("取消", null)
									.create().show();
							}
							else{
								SQLiteDatabase wdb = MyHelper.get(Notifications.this).getWritableDatabase();
								wdb.delete("notifications", "_id="+nid, null);
								wdb.close();
								refreshNotifications();
							}
							c.close();
						}
					}).setNegativeButton("取消", null).create().show();
					c.close();
					return false;
				}
			});
			
		}
	}

	protected void processNotify(long id) {
		Cursor c=listdb.rawQuery("select * from notifications where _id="+id, null);
		c.moveToFirst();
		switch (c.getInt(4)){
		case 1:
			if (processNotifyOnInvite(c)) removeNotify(id);
			break;
		case 2:
			processNotifyOnFriendAdd(c);
			break;
		case Dishes.NOTIFY_PLACE_CHANGED:
			processNotifyOnPlaceChange(c);
			break;
		case StateMachine.NOTIFY_LEFT_SESSION:
			processLeftSession(c);
			break;
		default:
			normalNotifyProcess(c);
			break;
		}
		c.close();
	}

	private void processLeftSession(Cursor c) {
		final long sessionid=Long.parseLong(c.getString(5));
		OnClickListener listener=new OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				doContinueOrder(sessionid);
			}
		};
		new AlertDialog.Builder(this).setTitle(getString(R.string.app_name))
		.setMessage(c.getString(1)+"，是否继续？")
		.setPositiveButton("是", listener)
		.setNegativeButton("否", null)
		.create().show();
	}

	private void processNotifyOnPlaceChange(Cursor c) {
		final int notifyid=c.getInt(0);
		final long sessionid=Long.parseLong(c.getString(5));
		removeNotify(notifyid);
		CharSequence[] items={
				"到新餐厅点餐",
				"退出聚餐",
		};
		OnClickListener listener=new OnClickListener(){
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which){
				case 0:
					doContinueOrder(sessionid);
					break;
				case 1:
					doQuitSession(sessionid);
					break;
				}
				dialog.dismiss();
			}
		};
		new AlertDialog.Builder(this).setTitle(c.getString(1))
		.setSingleChoiceItems(items, -1, listener)
		.create().show();
	}

	protected void doQuitSession(long sessionid) {
		final UserInfoData data = MyHelper.get(Notifications.this).getCurrUserInfoData(getWCAppContext().email);
		SQLiteDatabase db = MyHelper.get(this).getWritableDatabase();
		db.delete("sessionuser", "sessionid="+sessionid+" and uid="+data._id, null);
		db.close();
		Toast.makeText(this, "已退出", Toast.LENGTH_SHORT).show();
	}

	protected void doContinueOrder(long sessionid) {
		Cursor s=listdb.rawQuery("select * from sessions where _id="+sessionid, null);
		if (s.moveToFirst()){
			if (s.getInt(5)==2){
				new AlertDialog.Builder(Notifications.this).setTitle("点餐已完成").setIcon(R.drawable.icon)
				.setMessage("查看我的聚餐")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						changeToActivity(Sessions.class);
					}
				}).create().show();
			}
			else{
				getWCAppContext().sessionid=(int) sessionid;
				Cursor c=listdb.rawQuery("select * from sessions where _id="+sessionid, null);
				c.moveToFirst();
				getWCAppContext().restaurant=c.getInt(4);								
				changeToActivity(Dishes.class);
				c.close();
			}
		}
		else{
			Toast.makeText(this, "zhao bu dao "+sessionid, Toast.LENGTH_SHORT).show();
		}
		s.close();
	}

	private boolean processNotifyOnFriendAdd(Cursor c) {
		final int notifyid=c.getInt(0);
		removeNotify(notifyid);
		new AlertDialog.Builder(this).setTitle("消息中心")
		.setMessage(c.getString(1))
		.setPositiveButton("查看好友列表", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				changeToActivity(Friends.class);
			}
		}).create().show();
		return false;
	}

	private void normalNotifyProcess(Cursor c) {
		final int notifyid=c.getInt(0);
		new AlertDialog.Builder(this).setTitle("消息中心")
		.setMessage(c.getString(1))
		.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				removeNotify(notifyid);
			}
		}).create().show();
	}

	private void removeNotify(long id) {
		SQLiteDatabase db = MyHelper.get(this).getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put("done", 1);
		db.update("notifications", values, "_id="+id, null);
		db.close();
		new Handler().post(new Runnable(){
			@Override
			public void run() {
				HandleMessage(MSGTYPE.CHECK_NOTIFICATIONS, true, null);
				updateTopBar();
				refreshNotifications();
			}
		});
	}

	private boolean processNotifyOnInvite(Cursor c) {
		final long notifyid=c.getLong(0);
		String udata=c.getString(5);
		String[] ups=udata.split(",");
		final long sessionid=Long.parseLong(ups[0]);
		final long oldrestaurant=Long.parseLong(ups[1]);
		final UserInfoData data = MyHelper.get(Notifications.this).getCurrUserInfoData(getWCAppContext().email);
		Cursor s=listdb.rawQuery("select * from sessions where _id="+sessionid, null);
		if (s.moveToFirst()){
			if (s.getInt(5)==2){
				new AlertDialog.Builder(Notifications.this).setTitle("点餐已经完毕").setIcon(R.drawable.icon)
				.setMessage("是否查看详情")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						getWCAppContext().sessionid=(int) sessionid;
						changeToActivity(ShowSessionDetail.class);
						removeNotify(notifyid);
					}
				})
				.setNegativeButton("取消", null)
				.create().show();
			}
			else if (s.getLong(4)!=oldrestaurant){
				Cursor r=listdb.rawQuery("select * from restaurants where _id="+s.getLong(4), null);
				r.moveToFirst();
				new AlertDialog.Builder(Notifications.this).setTitle("发起人已变更聚餐地点")
					.setMessage("是否到新餐厅"+r.getString(1)+"点餐")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							DataMan.get(Notifications.this).confirmInvite(data._id,sessionid);
							getWCAppContext().sessionid=(int) sessionid;
							Cursor c=listdb.rawQuery("select * from sessions where _id="+sessionid, null);
							c.moveToFirst();
							getWCAppContext().restaurant=c.getInt(4);								
							changeToActivity(Dishes.class);
							c.close();
							removeNotify(notifyid);
						}
					})
					.setNegativeButton("取消", null).create().show();
				r.close();
			}
			else{
				new AlertDialog.Builder(Notifications.this).setTitle("聚餐确认").setIcon(R.drawable.icon)
				.setPositiveButton("去点餐", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						DataMan.get(Notifications.this).confirmInvite(data._id,sessionid);
						getWCAppContext().sessionid=(int) sessionid;
						Cursor c=listdb.rawQuery("select * from sessions where _id="+sessionid, null);
						c.moveToFirst();
						getWCAppContext().restaurant=c.getInt(4);								
						changeToActivity(Dishes.class);
						c.close();
						removeNotify(notifyid);
					}
				})
				.setNegativeButton("知道了", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						DataMan.get(Notifications.this).confirmInvite(data._id,sessionid);
						getWCAppContext().sessionid=(int) sessionid;
						removeNotify(notifyid);
					}
				}).create().show();
			}
			s.close();
		}
		else{
			Toast.makeText(this, "zhao bu dao "+sessionid, Toast.LENGTH_SHORT).show();
		}
		return false;
	}

	@Override
	public void onDestroy(){
		listdb.close();
		super.onDestroy();
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.notifications;
	}

}
